﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;

namespace Admin.NET.Application;

/// <summary>
/// 车辆信息表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class AppVehicleInfoService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<AppVehicleInfo> _appVehicleInfoRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public AppVehicleInfoService(SqlSugarRepository<AppVehicleInfo> appVehicleInfoRep, ISqlSugarClient sqlSugarClient)
    {
        _appVehicleInfoRep = appVehicleInfoRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询车辆信息表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询车辆信息表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<AppVehicleInfoOutput>> Page(PageAppVehicleInfoInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _appVehicleInfoRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.Title.Contains(input.Keyword) || u.VehicleType.Contains(input.Keyword) || u.Transmission.Contains(input.Keyword) || u.FuelType.Contains(input.Keyword) || u.EmissionStandard.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Title), u => u.Title.Contains(input.Title.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.VehicleType), u => u.VehicleType.Contains(input.VehicleType.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Transmission), u => u.Transmission.Contains(input.Transmission.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.FuelType), u => u.FuelType.Contains(input.FuelType.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.EmissionStandard), u => u.EmissionStandard.Contains(input.EmissionStandard.Trim()))
            .WhereIF(input.SellerId != null, u => u.SellerId == input.SellerId)
            .WhereIF(input.BrandId != null, u => u.BrandId == input.BrandId)
            .WhereIF(input.SeriesId != null, u => u.SeriesId == input.SeriesId)
            .WhereIF(input.ModelId != null, u => u.ModelId == input.ModelId)
            .WhereIF(input.Mileage != null, u => u.Mileage == input.Mileage)
            .WhereIF(input.ConditionLevel != null, u => u.ConditionLevel == input.ConditionLevel)
            .WhereIF(input.Status != null, u => u.Status == input.Status)
            .Select<AppVehicleInfoOutput>();
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取车辆信息表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取车辆信息表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<AppVehicleInfo> Detail([FromQuery] QueryByIdAppVehicleInfoInput input)
    {
        return await _appVehicleInfoRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加车辆信息表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加车辆信息表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddAppVehicleInfoInput input)
    {
        var entity = input.Adapt<AppVehicleInfo>();
        return await _appVehicleInfoRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新车辆信息表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新车辆信息表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateAppVehicleInfoInput input)
    {
        var entity = input.Adapt<AppVehicleInfo>();
        await _appVehicleInfoRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除车辆信息表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除车辆信息表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteAppVehicleInfoInput input)
    {
        var entity = await _appVehicleInfoRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _appVehicleInfoRep.FakeDeleteAsync(entity);   //假删除
        //await _appVehicleInfoRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除车辆信息表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除车辆信息表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteAppVehicleInfoInput> input)
    {
        var exp = Expressionable.Create<AppVehicleInfo>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _appVehicleInfoRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _appVehicleInfoRep.FakeDeleteAsync(list);   //假删除
        //return await _appVehicleInfoRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 导出车辆信息表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出车辆信息表记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageAppVehicleInfoInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportAppVehicleInfoOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "车辆信息表导出记录");
    }
    
    /// <summary>
    /// 下载车辆信息表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载车辆信息表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportAppVehicleInfoOutput>(), "车辆信息表导入模板");
    }
    
    /// <summary>
    /// 导入车辆信息表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入车辆信息表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportAppVehicleInfoInput, AppVehicleInfo>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.SellerId == null){
                            x.Error = "卖家Id不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.BrandId == null){
                            x.Error = "品牌Id不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.SeriesId == null){
                            x.Error = "车系Id不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.ModelId == null){
                            x.Error = "车型Id不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.Mileage == null){
                            x.Error = "里程数不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.ConditionLevel == null){
                            x.Error = "车况等级不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.Status == null){
                            x.Error = "状态不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<AppVehicleInfo>>();
                    
                    var storageable = _appVehicleInfoRep.Context.Storageable(rows)
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.Title), "标题不能为空")
                        .SplitError(it => it.Item.Title?.Length > 100, "标题长度不能超过100个字符")
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.VehicleType), "车辆类型不能为空")
                        .SplitError(it => it.Item.VehicleType?.Length > 20, "车辆类型长度不能超过20个字符")
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.Transmission), "变速箱类型不能为空")
                        .SplitError(it => it.Item.Transmission?.Length > 20, "变速箱类型长度不能超过20个字符")
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.FuelType), "燃油类型不能为空")
                        .SplitError(it => it.Item.FuelType?.Length > 20, "燃油类型长度不能超过20个字符")
                        .SplitError(it => it.Item.EmissionStandard?.Length > 20, "排放标准长度不能超过20个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
